import 'dart:io';
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as io;
import 'package:shelf_static/shelf_static.dart';
import 'package:socket_io/socket_io.dart' as socketIo;

void main() {
  // socketIOServer();
  // muxt();
  simple();
}

void simple(){
  final server = socketIo.Server();
  server.on("connection", (_) {
    final client = _ as socketIo.Socket;
    print("客户端id{${client.id}}已连接");
    
    client.on("msg", (msg){
      server.emit("msg", msg);
      print("msg is $msg");
    });

    client.on("disconnect", (_){
      print("客户端${client.id}断开连接");
    });
  });
  
  server.listen(3000).then((_)=>print("服务端已启动..."));
}

void muxt() async {

  final socketServer = socketIo.Server();
  socketServer.on("connection", (_) {
    final client = _ as socketIo.Socket;
    print("客户端id{${client.id}}已连接");

    client.on("disconnect", (_){
      print("客户端${client.id}断开连接");
    });
  });

  // socketServer.listen(3001).then((_) => print("服务端已启动..."));

  final handler = createStaticHandler('web',defaultDocument: 'index.html', listDirectories: true);
  final pipeline =const Pipeline().addMiddleware(logRequests()).addHandler(handler);
  // io.serve(pipeline, 'localhost', 3000).then((_)=>print("静态资源服务器启动..."));
  final server = await io.serve(pipeline, 'localhost', 3000);
  final r = await socketServer.attach(server);

}

void httpServer() async {
  // 定义静态资源的目录（如 "web" 文件夹）
  var handler = createStaticHandler('web',
      defaultDocument: 'index.html', listDirectories: true);

  // 将请求记录到控制台的中间件
  var pipeline =
      const Pipeline().addMiddleware(logRequests()).addHandler(handler);

  // 启动服务器
  var server = await io.serve(pipeline, 'localhost', 3000);
  print('静态资源服务器运行在 http://${server.address.host}:${server.port}');
}

void socketIOServer() {
  var io = socketIo.Server();

  io.origins("*:*"); // 允许所有来源连接

  io.on('connection', (client) {
    final socket = client as socketIo.Socket;
    print("客户端${socket.id}已连接");
    socket.emit("msg", "hello");
    socket.on("msg", (msg) {
      print("msg is $msg");
    });

    socket.on("disconnect", (_) {
      print("客户端${socket.id}断开连接");
    });
  });

  io.on("msg", (msg) {
    print("msg is $msg other");
  });

  io.listen(3000).then((_) => print("服务端已启动..."));
}

a() {
  var io = socketIo.Server();
  var nsp = io.of('/some');
  nsp.on('connection', (client) {
    print('connection /some');
    client.on('msg', (data) {
      print('data from /some => $data');
      client.emit('fromServer', "ok 2");
    });
  });
  io.on('connection', (client) {
    print('connection default namespace');

    io.emit("msg", "data");
    client.on('msg', (data) {
      print('data from default => $data');
      client.emit('fromServer', "ok");
    });
  });
  io.listen(3000);
}
